/*
 * @Author: shaohh  //公共的文件上传组件 只支持单个文件上传
 * @Date: 2022-09-27 16:40:42 
 * @Last Modified by: shaohh
 * @Last Modified time: 2022-11-10 16:07:38
 */
<template>
  <el-dialog
    title="导入"
    class="upload_dialog"
    v-if="dialogVisible"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="30%"
    :before-close="cancelDialog"
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.1)"   
  >
    <span slot="title" style="margin-left: 20px">导入</span>
    <div class="item_box">
      <div style="font-weight: bold">导入说明:</div>
      <slot />
      <div class="upload_box" v-if="uploadItem">
        <el-input v-model="file.name" disabled v-if="!activeItem"></el-input>
        <el-upload
          ref="upload"
          :class="['upload-demo', activeItem ? 'showItem' : '']"
          :action="apiAction"
          :headers="{ Accept: 'application/json', unionToken: token }"
          name="file"
          :limit="1"
          :accept="accept"
          :on-change="handleChange"
          :auto-upload="false"
          :on-error="uploadErr"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          :on-remove="cancelUpload"
        >
          <el-button
            style="margin-left: 10px"
            type="primary"
            v-if="file.name == ''"
            >选择文件</el-button
          >
        </el-upload>
        <el-button
          style="margin-left: 10px"
          type="primary"
          v-if="file.name != '' && !activeItem"
          @click="uploadExcle"
          >开始上传</el-button
        >
        <!-- <span v-if="file.name!=''&&activeItem" @click="cancelUpload" style="color:#999;cursor: pointer;" >取消</span> -->
      </div>
      <div v-else>
        <div class="afterUpload">
          <div><i class="el-icon-document"></i>{{ file.name }}</div>
          <div><i class="el-icon-close" @click="reUpload"></i></div>
        </div>
        <div class="btn_box">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
  
<script>
import { minioDeleteFile } from "@/api/upload.js";
export default {
  components: {},
  props: {
    api: {
      type: Function,
      required: true,
    },
    accept: {
      type: String,
      default: () => ".xls, .xlsx",
    },
  },
  data() {
    return {
      activeItem: false,
      dialogVisible: false,
      file: {
        name: "",
      },
      token: localStorage.getItem("unionToken"),
      cb: null, // 回调函数
      uploadItem: true,
      fd: null, // 二进制流文件
      fileUrl: "",
      loading: false,
      apiAction:'',
    };
  },
  mounted() {
    let config = require('@/config/env.'+process.env.NODE_ENV)
    this.apiAction = config.baseApi+'lab-bimpack/minioManage/minioUploadFile'
  },
  methods: {
    cancelDialog() {
      this.dialogVisible = false;
      this.deleteFile();
    },
    // 取消上传
    cancelUpload(file) {
      this.file = { name: "" };
      this.uploadItem = true;
      this.$refs.upload.clearFiles();
      this.activeItem = false;
    },
    // 上传之前把二进制流文件存起来
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 20;
      let fileSuffix = file.name.substring(file.name.lastIndexOf(".")); // 获取文件后缀
      let errMessage = [];
      if (!isLt2M) {
        errMessage.push(file.name + " 文件大小不能超过 20MB!");
      }
      if (this.accept.indexOf(fileSuffix) < 0) {
        errMessage.push(file.name + " 文件格式不正确");
      }
      if (errMessage.length > 0) {
        this.$sysUtil.showErr({ message: errMessage });
      }
      if (isLt2M && this.accept.indexOf(fileSuffix) > -1) {
        this.fd = new FormData();
        this.fd.append("file", file);
      }
      console.log(isLt2M && this.accept.indexOf(fileSuffix) > -1);
      return isLt2M && this.accept.indexOf(fileSuffix) > -1;
    },
    // 重新上传
    reUpload() {
      this.file = { name: "" };
      this.uploadItem = true;
      this.activeItem = false;
      this.deleteFile();
    },
    // 删除文件
    deleteFile() {
      if (this.fileUrl === "") {
        return;
      }
      minioDeleteFile({ fileNames: [this.fileUrl] })
        .then((res) => {
          this.fileUrl = "";
          console.log("删除成功");
        })
        .catch();
    },
    // 第一次上传失败 关闭弹窗
    uploadErr() {
      this.$message.error("导入失败,请重新上传文件");
      this.dialogVisible = false;
    },
    // 最后提交
    submit: _.debounce(
      function () {
        this.loading = true
        this.api(this.fd)
          .then((res) => {
            //根据新需求，报错信息会存储在返回的文件流中，返回为blob类型，若不能转换为json，则下载文件
            const reader = new FileReader();
            reader.onload = (event) => {
              try {
                // 将读取的string转换为json
                // 若果能转换成功 => 接口返回的是json数据，提示报错信息
                const json = JSON.parse(event.target.result);
                console.log(json);
                if (json.code == 500) {
                  this.$message.error(json.message);
                } else {
                  this.$message.success(json.message);
                  if (typeof this.cb === "function") {
                    this.cb();
                  }
                }
                this.loading = false
              } catch (err) {
                // 不能被转换成json => 接口返回的是blob, 下载blob文件
                const link = document.createElement("a");
                let blob = new Blob([res], {
                  type: "application/vnd.ms-excel",
                });
                link.style.display = "none";
                link.href = URL.createObjectURL(blob);
                let filename = this.file.name.split(".")[0];
                link.download = filename + ".xls";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                this.$message.error(filename + "导入错误");
                this.loading = false
              }
            };
            reader.readAsText(res);
          })
          .catch((err) => {
            this.$message.error("导入失败,请重新上传文件");
            console.log(err);
          })
          .finally(() => {
            this.dialogVisible = false;
            this.deleteFile();
          });
      },
      3000,
      { leading: true, trailing: false }
    ),
    // 第一次上传成功
    uploadSuccess(res, file) {
      this.uploadItem = false;
      this.fileUrl = res.data.nameByDel;
      // 判断上传成功之后弹窗关闭状态
      if (!this.dialogVisible) {
        this.deleteFile();
      }
    },
    // 自定义上传
    uploadExcle() {
      this.activeItem = true;
      this.$refs.upload.submit();
    },
    openDialog(cb) {
      this.activeItem = false;
      this.cb = cb;
      this.dialogVisible = true;
      this.uploadItem = true;
      this.file = {
        name: "",
      };
    },
    handleChange(file) {
      this.file = file;
    },
  },
};
</script>
  
<style lang="less" scoped>
.upload_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  margin-top: 20px;
}
.upload-demo {
  /deep/ .el-upload-list {
    display: none;
  }
}
.showItem {
  /deep/ .el-upload-list {
    display: block !important;
  }
}
.showItem /deep/ .el-upload-list {
  display: block !important;
}

.showItem {
  /deep/ .el-upload {
    display: none;
  }
}
.upload_dialog {
  /deep/ .el-dialog__header {
    padding-left: 0;
    padding-right: 0;
    border-bottom: 1px solid #dcdfe6;
    // margin :0 20px;
  }
}
.upload_dialog {
  /deep/ .el-dialog__body {
    padding-top: 12px;
  }
  .afterUpload {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    .el-icon-document {
      margin-right: 8px;
    }
    .el-icon-close {
      cursor: pointer;
    }
  }
  .el-icon-close {
    cursor: pointer;
  }
}
.btn_box {
  margin-top: 24px;
  text-align: right;
}
</style>
  